<script lang="ts" setup>
	import { onMounted, ref, computed, onBeforeMount } from 'vue'
	import lunar from 'chinese-lunar';
	import { onShow } from "@dcloudio/uni-app"
	import { DecryptAES, CheckTenantId } from "../../../common/Func.js"
	import { checkMoudleList } from "@/common/common.ts"
	import { schBaseInfo } from '@/api/school.js'
	import code from '../../../uni_modules/uview-plus/libs/config/props/code.js';
	import cookie from '@/store/cookie';
	import homeMoudle from './homeMoudle/homeMoudle.vue'
	import upDatePage from './homeMoudle/upDatePage.vue'
	import Upgrade from '@/common/Upgrade.js'
	import { getMoudleList, getBaseDecode } from '@/api/school.js'
	import { settingConfig } from '@/config/setting.config.js'
	import { userInfo } from '@/store/Pinia/userInfo.js'
	import { doActive, doActiveCheck } from '../../../api/device.js';

	const upgradeInstance = new Upgrade();
	const userInfoModel = userInfo()
	//验证码
	const isShowPage = ref(true)

	onBeforeMount(async () => {
		// cookie.clearAll();
		// #ifdef APP
		isShowPage.value = false
		// #endif
		if(uni.getStorageSync('activeState') === 'off' && !uni.getStorageSync('tenantId')) {
			isShowPage.value = false
		} else {
			await checkTenantId()
		}
		if (uni.getStorageSync('tenantId')){
			uni.getSystemInfo({
				success: async (info) => {
					const { data } = await doActiveCheck({
						deviceId: info.deviceId,
						tenantId: uni.getStorageSync('tenantId'),
						versionCode: info.appVersionCode,
						versionName: info.appVersion
					});
					if (data.data) {
						uni.setStorageSync('softName', data.data.softName);
					} else {
						uni.removeStorageSync('tenantId')
						isShowPage.value = false
					}
				}
			})
		}
		// CheckTenantId(uni.getStorageSync('tenantId'))
	})

	const authorizeCode = ref()
	const tenantIdIsAllow = ref(false)

	const tryThreeMinu = () => {
		// 判断是否已经测试过了
		let isAlreadyTry = uni.getStorageSync('tryFlag');
		if (isAlreadyTry == "" || isAlreadyTry === false || isAlreadyTry === null || isAlreadyTry == void 0) {
			uni.setStorageSync('tryFlag', true)
			uni.setStorageSync('tenantId', 'localhost')
			checkTenantId()
			setTimeout(() => {//没有开放测试逻辑
				uni.removeStorageSync('tenantId');
				uni.showToast({
					title: `测试时间到了`
				})
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/index/home/home'
					})
				}, 0)
			}, 1000 * 60 * 30)
		} else {
			uni.showToast({
				title: `每台设备只能测试一次哦`,
				icon: `none`
			})
		}

	}
	const checkTenantId = async () => {//检查tenanid
		let tenantId = uni.getStorageSync('tenantId');
		console.log('tenantId', tenantId, tenantId === "", tenantId == void 0, tenantId === null)
		if (tenantId === "" || tenantId == void 0 || tenantId === null) {
			isShowPage.value = false
			console.log(authorizeCode.value)
			if (authorizeCode.value) {
				try {
					console.log('aaaaaaaaaaa')
					const { data } = await doActive({
					  deviceId: uni.getStorageSync('deviceId'),
					  type: 'reservation',
					  licenseIdShort: authorizeCode.value
					})
					
					console.log('new', data)
					if(data.code === 200) {
						uni.showToast({
							title: '授权成功',
							icon: 'none',
							duration: 2000,
						})
						uni.setStorageSync('tenantId', data.data.tenantId)
						uni.setStorageSync('softName', data.data.softName)
						uni.setStorageSync('activeState', 'on')
						setTimeout(() => {
							isShowPage.value = true
						}, 1500)
					}
					// let code = DecryptAES(authorizeCode.value)
					// getBaseDecode({ code: authorizeCode.value }).then((res : any) => {
					// 	console.log('hhhhhhhhhhhhhhhhhhhh', res.data.data)
					// 	if (res.data.success && res.data.data.tenantId != '') {
					// 		checkTenantIdIsAllow(res.data.data.tenantId)
					// 	} else {
					// 		uni.showToast({
					// 			title: '授权码错误',
					// 			icon: 'none'
					// 		})
					// 	}
					// })

				} catch (e) {
					//TODO handle the exception
					isShowPage.value = false
					console.log('cuow')
				}
			}

		} else {
			console.log('eeeeeeeee')
			if(uni.getStorageSync('activeState') === 'off' && tenantId) {
				const { data } = await doActive({
			  deviceId: uni.getStorageSync('deviceId'),
			  tenantId: tenantId,
			  type: 'reservation'
			})
			if(data.code === 200) {
				uni.setStorageSync('softName', data.data.softName)
				uni.setStorageSync('activeState', 'on')
			}
			console.log('old', data)
			}
			isShowPage.value = true
		}
	}

	const checkTenantIdIsAllow = async (schoolDomain) => {//检查解析出来的tenanid是否合法
		let item = {
			code: schoolDomain
		}
		const codes = await schBaseInfo(item)
		if (codes?.data?.data !== null) {
			// uni.setStorageSync('domain', item.domain)
			uni.setStorageSync('tenantId', schoolDomain);
			uni.showToast({
				title: '授权成功',
				icon: 'none',
				duration: 2000,
			})

			setTimeout(() => {
				isShowPage.value = true
			}, 1500)

		}
		else {
			uni.showToast({
				title: '授权码错误',
				icon: 'none'
			})
		}

	}

	const checkTenantIdClose = () => {
		console.log('取消')
		authorizeCode.value = void 0

	}

	onShow(() => {
		// #ifdef APP-PLUS
		setTimeout(() => {
			plus.navigator.hideSystemNavigation() //隐藏虚拟按键
		}, 3000)
		// #endif

	})

	onMounted(() => {
		getTime();
		console.log('userinfo', userInfoModel.data.id)
		if (userInfoModel.data.id != null && userInfoModel.data.id != void 0)
			moudleList()
		// uni.clearStorageSync()
	})

	const getTimeData = ref(new Date());
	const getTime = () => {

		getTimeData.value = new Date();
		setTimeout(() => {
			getTime()
		}, 1000)
	}
	const dayOfWeek = computed(() => {
		const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];

		return days[getTimeData.value.getDay()];
	})


	const navigateTo = (e, flag = false) => {

		console.log('navigateTo', e,)
		let path = '';
		if (checkMoudleList(list.value, e)) {
			switch (e) {
				case 'appoint':
					path = '/pages/appointment/index'
					break;
				case 'article':
					path = '/pages/index/index'
					break;
				case 'consultCenter':
					path = '/pages/consultationCenter/index'
					break;
				case 'homeAudio':
					path = '/pages/musicRelax/index'
					break;
				case 'homeGame':
					console.log('homeGame', e,)
					if (userInfoModel.data.id == null && userInfoModel.data.id == void 0) { moudleList() }
					else {
						path = '/pages/game/gameList'
					}
					break;
				case 'evaluation':
					path = '/pages/evaluation/index/index'
			}

		} else {
			uni.showToast({
				title: '模块不可使用。',
				icon: 'error',
				mask: true
			})
		}

		if (path != '') {
			if (flag) {
				uni.navigateTo({
					url: path,
					animationType: 'none'
				})

			} else {
				uni.navigateTo({
					url: path
				})
			}

		}
	}

	const flag = ref(false)

	const showPopup = ref(false)



	const local = ref(0)
	const latest = ref(0)
	const dowUrl = ref('')
	const checkVersion = async () => {

		const { localVersion, latestObj } = await upgradeInstance.checkVersionOnlyOne();
		local.value = localVersion;
		latest.value = latestObj.versionCode;
		dowUrl.value = latestObj.url;
		if (latest.value != undefined && latest.value != local.value && latest.value != null) {
			// upgradeInstance.updatePackage(latestObj.url)
			showPopup.value = true
		} else {
			uni.showToast({
				title: `当前已经是最新版本：V${local.value ?? '1.0.0'},无需更新`,
				icon: 'none'
			})
		}


	}


	const downloadLatestVersion = () => {
		if (local.value < latest.value) {
			// plus.runtime.openWeb(dowUrl.value)
			upgradeInstance.setLastVersion(latest.value)
			upgradeInstance.updatePackage(dowUrl.value);
		}
		showPopup.value = false
	}

	const list = ref(['appoint', 'article', 'consultCenter', 'homeAudio', 'evaluation', 'homeGame'])
	const moudleList = () => {
		let item = {
			funcModuleType: 'yyj',
			size: 100
		}
		getMoudleList(item).then(res => {
			if (res.data.success) {
				console.log('res.data.data.records', res.data.data.records)
				list.value = res.data.data.records.map((item) => { return item['funcModuleKey'] })
			}
		})
	}
	const timer = ref(null)
	const handleEnd = () => {
		timer.value.resetTime()
	}
</script>

<template>
	<articleTable ref="timer"></articleTable>
	<view @touchend="handleEnd" class="wh100p flex-center align-center fontPage" :class="isShowPage?'opacity0':''"
		style="position: absolute;background-color: aliceblue;">
		<u-popup :show="true" mode="center" round='10'>
			<view class="border-radius8 flex-column "
				style="width:600px;height:200px;padding:25px 35px 20px;box-sizing: border-box;">
				<text class="font24" style="flex: 2;">请输入授权码</text>
				<view style="flex: 1;"><input style="border-bottom: 1px silver solid;" v-model="authorizeCode" /></view>
				<view class="flex-end" style="flex: 1;align-items: flex-end;">
					<!-- <text class="click" style="color: #179083;padding:5px 10px ;" >试用</text> -->
					<view class="flex-end" style="flex: 1;">
						<text class="click" style="color: #179083;padding:5px 10px ;"
							@tap="checkTenantIdClose">取消</text><text class="click"
							style="color: #179083;padding:5px 10px ;" @tap.stop="checkTenantId">确定</text>
					</view>
				</view>
			</view>
		</u-popup>
	</view>

	<u-modal class="absolute" :show="showPopup" showCancelButton width="550rpx" @confirm="downloadLatestVersion"
		@cancel="showPopup = false" confirmColor='#ec9c01'>
		<view>
			<text style="color:4c4c4c;">{{`当前版本为${local}，最新版本为${latest??local}`}}{{false? '，是否需要重新安装最新版本？':''}}</text>
		</view>
	</u-modal>
	<view @touchend="handleEnd" class="wh100p relative flex-column">
		<view class="bg flex-center">
			<img v-if="settingConfig.bgIcon!=null" style="width:50%;opacity: 0.1;"
				:src="'@/../static/img/'+settingConfig.bgIcon" />
		</view>
		<tabbar class="absolute" style="top: 1%;z-index: 999;"></tabbar>

		<view class="  body-box flex-column" style="flex: 1;">
			<view class=" flex-center w100p  relative align-center" style="flex: 1;">
				<view class="flex-center title align-center" style="margin: 0 auto;height: 40%;">
					<img v-if="settingConfig.bgIcon!=null" :src="'@/../static/img/'+settingConfig.bgIcon" class="mr20"
						style="width: 75px;" />
					<!-- {{settingConfig.bgIcon}} -->
					<text>{{settingConfig.title}}</text>
				</view>
			</view>
			<view class="" style="flex:5;">
				<view style="height: 100%;">
					<swiper class="wh100p " style="display: flex;justify-content: flex-end;">
						<swiper-item>
							<homeMoudle @toMoudle="navigateTo" @handleEnd="handleEnd"></homeMoudle>
						</swiper-item>
						<swiper-item>
							<upDatePage @checkVersion="checkVersion" @handleEnd="handleEnd"></upDatePage>
						</swiper-item>
					</swiper>
				</view>
			</view>
		</view>
	</view>
</template>

<style>
	.bg {
		background: linear-gradient(90deg, #0078BB 0%, #003E94 100%);
		background-size: cover;
		/* 背景图放大并保持纵横比 */
		background-repeat: no-repeat;
		/* 背景图不重复 */
		filter: blur(2px);
		width: 100%;
		height: 100%;
		position: absolute;
	}

	.body-box {
		max-width: 1400px;
		width: 1400px;
		/* height: 100%; */
		/* background-color: red; */
		box-sizing: border-box;
		/* padding: 5% 0; */
		/* z-index: 99; */
		margin: 0 auto;
	}

	.title {
		color: #FFF;
		font-family: PingFang SC;
		font-size: 50px;
		font-style: normal;
		font-weight: 600;
		line-height: 76.8px;
		/* 128% */
	}

	.opacity0 {
		/* animation: hidden 1s ease-in-out; */
		opacity: 0;
		visibility: hidden;
		z-index: 1;
	}
</style>